import sys
import os
import pandas as pd
import database
import logging
from datetime import datetime

# 配置日志
logging.basicConfig(
    filename='app.log',
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                             QTreeWidget, QTextEdit, QPushButton, QLineEdit, QLabel, QMessageBox,
                             QInputDialog, QFormLayout, QDialog, QFontComboBox,
                             QSpinBox, QToolBar, QStatusBar, QSplitter, QTreeWidgetItem,
                             QFileDialog, QMenu)
from PyQt6.QtGui import QFont, QIcon, QTextCharFormat, QFontDatabase, QAction, QKeySequence, QTextCursor, QShortcut
from PyQt6.QtCore import Qt, QSize, QPoint, QTimer
from database import connect_db, ensure_user_root_folder, is_root_folder, search_files, DB_NAME


class PyQtMainWindow(QMainWindow):
    def __init__(self, user_id):
        super().__init__()
        self.user_id = user_id
        self.current_file_id = None
        self.current_folder_id = None
        self.need_save = False
        # 设置主题颜色
        self.theme = {
            'primary': '#1a73e8',
            'primary_light': '#d2e3fc',
            'secondary': '#f1f3f4',
            'text': '#202124',
            'text_light': '#5f6368',
            'background': '#ffffff',
            'panel_bg': '#f8f9fa',
            'border': '#dadce0'
        }
        # 设置窗口图标
        icon_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'icon.ico')
        if os.path.exists(icon_path):
            self.setWindowIcon(QIcon(icon_path))
        self.init_ui()
        self.load_user_data()
        self.apply_styles()


    def init_ui(self):
        # 设置窗口
        self.setWindowTitle("小兔文档")
        self.resize(1200, 800)  # 增大窗口尺寸
        self.setMinimumSize(1000, 600)

        # 创建菜单栏
        self.create_menu_bar()

        # 创建中心部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        # 主布局
        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(10)

        # 搜索功能已移至菜单栏中的工具菜单

        # ---------- 三栏布局区域 ----------
        # 创建分割器（三栏布局）
        main_splitter = QSplitter(Qt.Orientation.Horizontal)
        main_layout.addWidget(main_splitter)

        # ---------- 左一栏：文件夹列表 ----------
        folder_panel = QWidget()
        folder_layout = QVBoxLayout(folder_panel)
        folder_layout.setContentsMargins(5, 5, 5, 5)
        folder_layout.setSpacing(10)

        # 文件夹标题区域
        folder_header_layout = QHBoxLayout()
        self.root_folder_label = QLabel("文件夹管理")
        self.root_folder_label.setFont(QFont("SimSun", 12, QFont.Weight.Bold))
        self.add_folder_btn = QPushButton("新建")
        self.add_folder_btn.clicked.connect(self.add_folder)
        self.add_folder_btn.setMaximumWidth(60)
        folder_header_layout.addWidget(self.root_folder_label)
        folder_header_layout.addWidget(self.add_folder_btn)
        folder_header_layout.addStretch(1)
        folder_layout.addLayout(folder_header_layout)  

        # 文件夹树
        self.folder_tree = QTreeWidget()
        self.folder_tree.setHeaderLabel("文件夹列表")
        self.folder_tree.itemClicked.connect(self.on_folder_clicked)
        # 设置右键菜单
        self.folder_tree.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.folder_tree.customContextMenuRequested.connect(self.show_folder_context_menu)
        folder_layout.addWidget(self.folder_tree)

        main_splitter.addWidget(folder_panel)

        # ---------- 左二栏：文件列表 ----------
        file_panel = QWidget()
        file_layout = QVBoxLayout(file_panel)
        file_layout.setContentsMargins(5, 5, 5, 5)
        file_layout.setSpacing(10)

        # 文件列表标题区域
        file_header_layout = QHBoxLayout()
        self.current_folder_label = QLabel("当前文件夹")
        self.current_folder_label.setFont(QFont("SimSun", 12, QFont.Weight.Bold))
        self.new_file_btn = QPushButton("+")
        self.new_file_btn.clicked.connect(self.add_file)
        self.new_file_btn.setMaximumWidth(30)
        file_header_layout.addWidget(self.current_folder_label)
        file_header_layout.addWidget(self.new_file_btn)
        file_header_layout.addStretch(1)
        file_layout.addLayout(file_header_layout)

        # 文件列表
        self.file_list = QTreeWidget()
        self.file_list.setHeaderLabel("文件列表")
        self.file_list.itemClicked.connect(self.on_file_clicked)
        # 设置右键菜单
        self.file_list.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.file_list.customContextMenuRequested.connect(self.show_file_context_menu)
        file_layout.addWidget(self.file_list)

        main_splitter.addWidget(file_panel)

        # ---------- 右侧栏：文本编辑栏 ----------
        editor_panel = QWidget()
        editor_layout = QVBoxLayout(editor_panel)
        editor_layout.setContentsMargins(5, 5, 5, 5)
        editor_layout.setSpacing(10)

        # 添加工具栏
        self.create_toolbar(editor_layout)

        # 文件名输入
        self.filename_edit = QLineEdit()
        self.filename_edit.setPlaceholderText("请输入文件名...")
        self.filename_edit.setFont(QFont("SimSun", 12))
        self.filename_edit.textChanged.connect(self.on_filename_changed)
        editor_layout.addWidget(self.filename_edit)

        # 富文本编辑器
        self.editor = QTextEdit()
        self.editor.setFont(QFont("SimSun", 11))
        self.editor.setAcceptRichText(True)
        self.editor.textChanged.connect(self.on_text_changed)
        editor_layout.addWidget(self.editor)

        main_splitter.addWidget(editor_panel)

        # 设置三栏宽度比例
        main_splitter.setSizes([200, 300, 700])

        # ---------- 保存定时器初始化 ----------
        # 防抖定时器（实时保存）
        self.debounce_timer = QTimer(self)
        self.debounce_timer.setSingleShot(True)
        self.debounce_timer.timeout.connect(self.save_file)
        self.debounce_timer.setInterval(500)  # 500毫秒防抖

        # 自动保存定时器
        self.auto_save_timer = QTimer(self)
        self.auto_save_timer.timeout.connect(self.auto_save)
        self.auto_save_timer.setInterval(1000)  # 1秒自动保存
        self.auto_save_timer.start()


        # 状态栏
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        self.status_bar.showMessage("就绪")


        # 添加查找功能快捷键 Ctrl+F
        self.find_shortcut = QShortcut(QKeySequence("Ctrl+F"), self)
        self.find_shortcut.activated.connect(self.show_find_dialog)

        # 添加纯文本粘贴快捷键 Ctrl+Shift+V
        self.paste_plain_shortcut = QShortcut(QKeySequence("Ctrl+Shift+V"), self)
        self.paste_plain_shortcut.activated.connect(self.paste_plain_text)


    def show_find_dialog(self):
        """显示查找对话框"""
        # 创建查找对话框
        find_dialog = QDialog(self)
        find_dialog.setWindowTitle("查找")
        find_dialog.setFixedSize(300, 100)


        # 创建布局
        layout = QFormLayout(find_dialog)


        # 添加查找输入框
        self.find_input = QLineEdit(find_dialog)
        layout.addRow("查找内容:", self.find_input)


        # 添加按钮布局
        btn_layout = QHBoxLayout()
        find_btn = QPushButton("查找下一个")
        find_btn.clicked.connect(self.find_next)
        cancel_btn = QPushButton("取消")
        cancel_btn.clicked.connect(find_dialog.close)


        btn_layout.addWidget(find_btn)
        btn_layout.addWidget(cancel_btn)
        layout.addRow(btn_layout)


        # 设置对话框样式
        find_dialog.setStyleSheet(f'''
            QDialog {{background-color: {self.theme['background']};}}
            QLabel {{color: {self.theme['text']};}}
            QLineEdit {{border: 1px solid {self.theme['border']}; border-radius: 4px; padding: 6px;}}
            QPushButton {{background-color: {self.theme['secondary']}; border-radius: 4px; padding: 6px 12px;}}
            QPushButton:hover {{background-color: {self.theme['primary_light']};}}
            QPushButton:pressed {{background-color: {self.theme['primary']}; color: white;}}
            '''
        )


        find_dialog.exec()


    def find_next(self):
        """查找下一个匹配项"""
        search_text = self.find_input.text().strip()
        if not search_text:
            return


        # 使用QTextEdit的find方法查找文本
        if not self.editor.find(search_text):
            # 如果到达文本末尾，从头开始查找
            cursor = self.editor.textCursor()
            cursor.movePosition(cursor.MoveOperation.Start)
            self.editor.setTextCursor(cursor)
            if not self.editor.find(search_text):
                QMessageBox.information(self, "查找完成", f"未找到 '{search_text}'")


    def perform_search(self):
        """执行搜索并显示结果"""
        # 弹出对话框让用户输入搜索关键字
        keyword, ok = QInputDialog.getText(self, "搜索", "请输入搜索关键字:")
        if not ok or not keyword.strip():
            return
        
        keyword = keyword.strip()
        
        try:
            results = search_files(self.user_id, keyword)
            self.file_list.clear()
            
            for file_id, name, content, folder_id in results:
                item = QTreeWidgetItem([name])
                item.setData(0, Qt.ItemDataRole.UserRole, file_id)
                # 可以添加一个标记指示匹配类型
                match_type = "标题" if keyword.lower() in name.lower() else "内容"
                item.setToolTip(0, f"匹配{match_type}: {keyword}")
                self.file_list.addTopLevelItem(item)
            
            self.status_bar.showMessage(f"找到 {len(results)} 个匹配结果")
        except Exception as e:
            QMessageBox.critical(self, "搜索错误", f"搜索失败: {str(e)}")


    def clear_search(self):
        """清除搜索结果，恢复文件列表"""
        if self.current_folder_id:
            self.load_files(self.current_folder_id)
        else:
            self.file_list.clear()
        self.status_bar.showMessage("就绪")


    def create_toolbar(self, parent_layout):
        """创建富文本编辑工具栏"""
        toolbar = QToolBar()
        toolbar.setIconSize(QSize(20, 20))
        toolbar.setStyleSheet(f"background-color: {self.theme['panel_bg']};")


        # 添加分隔线和图标
        self.add_toolbar_separator(toolbar, "字体设置")


        # 字体选择
        font_combo = QFontComboBox()
        font_combo.setMinimumWidth(120)
        # 设置默认字体为宋体
        font_combo.setCurrentFont(QFont("SimSun"))
        font_combo.currentFontChanged.connect(lambda font: self.editor.setCurrentFont(font))
        toolbar.addWidget(QLabel("字体:"))
        toolbar.addWidget(font_combo)


        # 字号选择
        font_size = QSpinBox()
        font_size.setRange(6, 72)
        font_size.setValue(11)
        font_size.valueChanged.connect(lambda size: self.editor.setFontPointSize(size))
        toolbar.addWidget(QLabel("字号:"))
        toolbar.addWidget(font_size)


        self.add_toolbar_separator(toolbar, "文本格式")


        # 加粗 - 修复：移除文本占位符图标，直接使用文本
        bold_action = QAction("加粗", self)
        bold_action.setCheckable(True)
        bold_action.triggered.connect(lambda: self.editor.setFontWeight(
            QFont.Weight.Bold if bold_action.isChecked() else QFont.Weight.Normal))
        toolbar.addAction(bold_action)


        # 斜体 - 修复：移除文本占位符图标，直接使用文本
        italic_action = QAction("斜体", self)
        italic_action.setCheckable(True)
        italic_action.triggered.connect(lambda: self.editor.setFontItalic(italic_action.isChecked()))
        toolbar.addAction(italic_action)


        # 下划线 - 修复：移除文本占位符图标，直接使用文本
        underline_action = QAction("下划线", self)
        underline_action.setCheckable(True)
        underline_action.triggered.connect(lambda: self.editor.setFontUnderline(underline_action.isChecked()))
        toolbar.addAction(underline_action)

        # 清除格式
        clear_format_action = QAction("清除格式", self)
        clear_format_action.triggered.connect(self.clear_format)
        toolbar.addAction(clear_format_action)

        # 字体颜色
        color_action = QAction("字体颜色", self)
        color_action.triggered.connect(self.set_text_color)
        toolbar.addAction(color_action)

        # 高亮显示
        highlight_action = QAction("高亮显示", self)
        highlight_action.triggered.connect(self.set_text_highlight)
        toolbar.addAction(highlight_action)

        parent_layout.addWidget(toolbar)


    def add_toolbar_separator(self, toolbar, title):
        """添加工具栏分隔线和标题"""
        toolbar.addSeparator()
        label = QLabel(f" {title} ")
        label.setStyleSheet(f"background-color: {self.theme['primary_light']}; color: {self.theme['primary']}; border-radius: 4px;")
        toolbar.addWidget(label)
        toolbar.addSeparator()


    def create_menu_bar(self):
        """创建菜单栏"""
        # 获取菜单栏
        menu_bar = self.menuBar()
        
        # ---------- 文件菜单 ----------
        file_menu = menu_bar.addMenu("文件")
        
        # 新建文件
        new_file_action = QAction("新建文件", self)
        new_file_action.setShortcut("Ctrl+N")
        new_file_action.triggered.connect(self.add_file)
        file_menu.addAction(new_file_action)
        
        # 新建文件夹
        new_folder_action = QAction("新建文件夹", self)
        new_folder_action.triggered.connect(lambda: self.add_folder())
        file_menu.addAction(new_folder_action)
        
        file_menu.addSeparator()
        
        # 保存文件
        save_action = QAction("保存文件", self)
        save_action.setShortcut("Ctrl+S")
        save_action.triggered.connect(self.save_file)
        file_menu.addAction(save_action)
        
        file_menu.addSeparator()
        
        # 打印文件
        print_action = QAction("打印文件", self)
        print_action.setShortcut("Ctrl+P")
        print_action.triggered.connect(self.print_document)
        file_menu.addAction(print_action)
        
        file_menu.addSeparator()      
        
        # 关闭程序
        exit_action = QAction("关闭", self)
        exit_action.setShortcut("Ctrl+Q")
        exit_action.triggered.connect(self.close_application)
        file_menu.addAction(exit_action)
        
        # ---------- 工具菜单 ----------
        tools_menu = menu_bar.addMenu("工具")
        
        # 搜索功能
        search_action = QAction("搜索", self)
        search_action.setShortcut("Ctrl+F")
        search_action.triggered.connect(self.perform_search)
        tools_menu.addAction(search_action)
        
        # 查找功能
        find_action = QAction("查找", self)
        find_action.setShortcut("Ctrl+Shift+F")
        find_action.triggered.connect(self.show_find_dialog)
        tools_menu.addAction(find_action)
        
        tools_menu.addSeparator()
        
        # 数据备份
        backup_action = QAction("数据备份", self)
        backup_action.triggered.connect(self.backup_database)
        tools_menu.addAction(backup_action)
        
        # 数据恢复
        restore_action = QAction("数据恢复", self)
        restore_action.triggered.connect(self.restore_database)
        tools_menu.addAction(restore_action)
        
        # ---------- 帮助菜单 ----------
        help_menu = menu_bar.addMenu("帮助")
        
        # 版本信息
        version_action = QAction("版本", self)
        version_action.triggered.connect(self.show_version_info)
        help_menu.addAction(version_action)
        
        # 更新信息
        update_action = QAction("更新", self)
        update_action.triggered.connect(self.show_update_info)
        help_menu.addAction(update_action)
        
        # 关于信息
        about_action = QAction("关于", self)
        about_action.triggered.connect(self.show_about_info)
        help_menu.addAction(about_action)
        
        
    def show_version_info(self):
        """显示版本信息"""
        QMessageBox.information(self, "版本信息", "小兔文档 v1.14.0\n\n简单、高效、安全的文档管理工具")
        
    
    def show_update_info(self):
        """显示更新信息"""
        from PyQt6.QtWidgets import QMessageBox
        reply = QMessageBox.question(
            self, "检查更新", 
            "即将跳转到版本更新页面，是否继续？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
        )
        if reply == QMessageBox.StandardButton.Yes:
            import webbrowser
            webbrowser.open("https://gitcode.com/2503_92510982/rabbitdoc/releases")
            
    
    def show_about_info(self):
        """显示关于信息"""
        from PyQt6.QtWidgets import QMessageBox
        reply = QMessageBox.question(
            self, "关于小兔文档", 
            "即将跳转到官网介绍页面，是否继续？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
        )
        if reply == QMessageBox.StandardButton.Yes:
            import webbrowser
            webbrowser.open("https://fjtools.cn/?T1755441589")
            
            
    def print_document(self):
        """打印文档内容"""
        from PyQt6.QtPrintSupport import QPrinter, QPrintDialog
        from PyQt6.QtWidgets import QMessageBox
        
        # 检查是否有内容可打印
        if not self.editor.toPlainText().strip():
            QMessageBox.information(self, "提示", "没有可打印的内容")
            return
        
        # 获取文档标题和内容
        document_title = self.filename_edit.text() or "未命名文档"
        document_content = self.editor.toHtml()
        
        # 创建打印机对象
        printer = QPrinter(QPrinter.PrinterMode.HighResolution)
        
        # 显示打印对话框
        dialog = QPrintDialog(printer, self)
        if dialog.exec() != QPrintDialog.DialogCode.Accepted:
            return
        
        # 创建打印文档
        from PyQt6.QtGui import QTextDocument
        doc = QTextDocument()
        
        # 设置文档内容（包含标题和正文）
        formatted_content = f"<h1>{document_title}</h1><hr>{document_content}"
        doc.setHtml(formatted_content)
        
        # 执行打印
        doc.print(printer)
        
        # 显示打印成功消息
        self.status_bar.showMessage(f"已打印文档: {document_title}")      
        
    
    def close_application(self):
        """关闭程序"""
        self.close()
        
        
    def get_icon(self, icon_name):
        """获取图标（实际项目中应替换为真实图标）"""
        # 这里使用简单文本作为占位符，实际应用中应使用QIcon
        icons = {
            'bold': 'B',
            'italic': 'I',
            'underline': 'U'
        }
        return icons.get(icon_name, '')      


    def load_user_data(self):
        """加载用户数据：文件夹和文件"""
        self.load_folders()



    def load_folders(self):
        """加载文件夹树形结构"""
        self.folder_tree.clear()  # 将 folder_list 改为 folder_tree
        conn = connect_db()
        cursor = conn.cursor()
        
        try:
            # 确保根文件夹存在并获取ID
            root_folder_id = ensure_user_root_folder(self.user_id)
            if not root_folder_id:
                QMessageBox.critical(self, "错误", "无法创建或找到根文件夹")
                return
            
            # 获取根文件夹名称
            cursor.execute("SELECT name FROM folders WHERE id=?", (root_folder_id,))
            root_name = cursor.fetchone()[0]
            
            # 创建根节点
            root_item = QTreeWidgetItem(self.folder_tree, [root_name])
            root_item.setData(0, Qt.ItemDataRole.UserRole, root_folder_id)  # Updated line
            
            # 递归加载子文件夹
            self.load_subfolders(cursor, root_item, root_folder_id)
            
            # 展开根节点
            self.folder_tree.expandItem(root_item)
            
            # 默认选中根文件夹
            self.folder_tree.setCurrentItem(root_item)
            self.on_folder_clicked(root_item, 0)
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载文件夹失败: {str(e)}")
        finally:
            conn.close()
    
    def load_subfolders(self, cursor, parent_item, parent_id):
        """递归加载子文件夹"""
        cursor.execute(
            "SELECT id, name FROM folders WHERE user_id=? AND parent_id=? ORDER BY display_order",
            (self.user_id, parent_id)
        )
        subfolders = cursor.fetchall()
    
        for folder_id, name in subfolders:
            item = QTreeWidgetItem(parent_item, [name])
            item.setData(0, Qt.ItemDataRole.UserRole, folder_id)  # Updated line
            
            # 递归加载孙子文件夹
            self.load_subfolders(cursor, item, folder_id)    


    def load_files(self, folder_id):
        """从数据库加载指定文件夹下的文件"""
        self.file_list.clear()
        conn = connect_db()
        cursor = conn.cursor()
        cursor.execute("SELECT id, name FROM files WHERE folder_id=? ORDER BY name DESC", (folder_id,))
        files = cursor.fetchall()
        conn.close()


        for file_id, name in files:
            item = QTreeWidgetItem([name])
            item.setData(0, Qt.ItemDataRole.UserRole, file_id)
            self.file_list.addTopLevelItem(item)


    def on_folder_clicked(self, item, column):
        """文件夹点击事件"""
        folder_id = item.data(0, Qt.ItemDataRole.UserRole)
        folder_name = item.text(0)
        self.current_folder_id = folder_id
        
        # 更新当前文件夹标签显示
        self.current_folder_label.setText(f"{folder_name}")
        
        # 加载该文件夹下的文件
        self.load_files(folder_id)
        
        # 根据是否为根文件夹启用/禁用按钮
        is_root = folder_id and is_root_folder(folder_id)
        if hasattr(self, 'del_folder_btn'):
            self.del_folder_btn.setEnabled(not is_root)
        if hasattr(self, 'rename_folder_btn'):
            self.rename_folder_btn.setEnabled(not is_root)


    def load_file_content(self, file_id):
        """加载文件内容"""
        conn = connect_db()
        cursor = conn.cursor()
        cursor.execute("SELECT name, content FROM files WHERE id=?", (file_id,))
        file_data = cursor.fetchone()
        conn.close()


        if file_data:
            self.current_file_id = file_id
            self.filename_edit.setText(file_data[0])
            self.editor.setHtml(file_data[1])
            self.status_bar.showMessage(f"已加载文件: {file_data[0]}")

    def clear_format(self):
        """清除选中文本的格式"""
        cursor = self.editor.textCursor()
        if cursor.hasSelection():
            # 获取选中的文本
            selected_text = cursor.selectedText()
            # 创建新的文本格式
            format = QTextCharFormat()
            # 设置纯文本
            cursor.insertText(selected_text, format)
            self.status_bar.showMessage("已清除文本格式")
        else:
            QMessageBox.information(self, "提示", "请先选择要清除格式的文本")

    def paste_plain_text(self):
        """纯文本粘贴 (Ctrl+Shift+V)"""
        clipboard = QApplication.clipboard()
        plain_text = clipboard.text()
        if plain_text:
            cursor = self.editor.textCursor()
            # 插入纯文本
            cursor.insertText(plain_text)
            self.status_bar.showMessage("已粘贴纯文本")
        else:
            self.status_bar.showMessage("剪贴板中没有文本")

    def set_text_color(self):
        """设置字体颜色"""
        from PyQt6.QtWidgets import QColorDialog
        from PyQt6.QtGui import QColor

        cursor = self.editor.textCursor()
        if cursor.hasSelection():
            # 获取当前颜色
            current_color = cursor.charFormat().foreground().color()
            # 弹出颜色选择对话框
            color = QColorDialog.getColor(current_color, self, "选择字体颜色")
            if color.isValid():
                # 创建文本格式
                format = QTextCharFormat()
                format.setForeground(color)
                # 应用格式
                cursor.mergeCharFormat(format)
                self.editor.setTextCursor(cursor)
                self.status_bar.showMessage("已设置字体颜色")
        else:
            QMessageBox.information(self, "提示", "请先选择要设置颜色的文本")

    def set_text_highlight(self):
        """设置文本高亮显示"""
        from PyQt6.QtWidgets import QColorDialog
        from PyQt6.QtGui import QColor

        cursor = self.editor.textCursor()
        if cursor.hasSelection():
            # 获取当前高亮颜色
            current_color = cursor.charFormat().background().color()
            # 弹出颜色选择对话框
            color = QColorDialog.getColor(current_color, self, "选择高亮颜色")
            if color.isValid():
                # 创建文本格式
                format = QTextCharFormat()
                format.setBackground(color)
                # 应用格式
                cursor.mergeCharFormat(format)
                self.editor.setTextCursor(cursor)
                self.status_bar.showMessage("已设置文本高亮")
        else:
            QMessageBox.information(self, "提示", "请先选择要高亮的文本")


    def on_file_clicked(self, item, column):
        """文件点击事件"""
        file_id = item.data(0, Qt.ItemDataRole.UserRole)
        if file_id:
            self.load_file_content(file_id)


    def on_text_changed(self):
        """文本内容变化事件"""
        # 当有当前文件ID，或文件名和内容都不为空时，标记为需要保存
        has_filename = bool(self.filename_edit.text().strip())
        has_content = bool(self.editor.toPlainText().strip())
        
        if self.current_file_id or (has_filename and has_content):
            self.need_save = True
            # 重置防抖定时器
            self.debounce_timer.stop()
            self.debounce_timer.start(1000)
    
    def on_filename_changed(self):
        """文件名变化事件 - 在有标题和内容的情况下触发自动保存，并同步更新文件列表标题"""
        # 当文件名和内容都不为空时，标记为需要保存
        has_filename = bool(self.filename_edit.text().strip())
        has_content = bool(self.editor.toPlainText().strip())
        
        if has_filename and has_content:
            self.need_save = True
            # 保存文件前记录是否为新文件
            is_new_file_before_save = self.current_file_id is None
            # 立即保存
            self.save_file(show_message=False)
            
            if is_new_file_before_save:
                # 如果是新文件，刷新整个文件列表
                if self.current_folder_id:
                    self.load_files(self.current_folder_id)
            elif self.current_file_id:
                # 如果是已有文件，只更新文件列表中的标题
                for i in range(self.file_list.topLevelItemCount()):
                    item = self.file_list.topLevelItem(i)
                    if item and item.data(0, Qt.ItemDataRole.UserRole) == self.current_file_id:
                        # 更新文件列表中的标题
                        item.setText(0, self.filename_edit.text().strip())
                        break
            
            current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            self.statusBar().showMessage(f"标题变更，自动保存成功 [{current_time}]")

    def add_folder(self, parent_folder_id=None):
        """添加文件夹（支持多级）"""
        # 如果提供了parent_folder_id，则直接使用
        if parent_folder_id is not None:
            parent_id = parent_folder_id
        else:
            # 否则获取当前选中的文件夹，如无选中则使用根文件夹
            current_item = self.folder_tree.currentItem()  
            if not current_item:
                # 尝试获取根文件夹
                root_item = self.folder_tree.topLevelItem(0)  
                if not root_item:
                    QMessageBox.warning(self, "提示", "无法找到根文件夹，请刷新后重试")
                    return
                current_item = root_item
            
            parent_id = current_item.data(0, Qt.ItemDataRole.UserRole) 
        
        # 检查parent_id是否有效
        if not parent_id:
            # 尝试获取用户的根文件夹
            root_folder_id = ensure_user_root_folder(self.user_id)
            if not root_folder_id:
                QMessageBox.warning(self, "提示", "无法找到有效的父文件夹")
                return
            parent_id = root_folder_id
            logging.info(f"使用根文件夹作为父文件夹: {parent_id}")
            
        name, ok = QInputDialog.getText(self, "新建文件夹", "请输入文件夹名称:")
        
        if ok and name.strip():
            logging.info(f"尝试创建文件夹: {name}, 父文件夹ID: {parent_id}")
            conn = connect_db()
            cursor = conn.cursor()
            try:
                # 检查父文件夹是否存在
                cursor.execute("SELECT COUNT(*) FROM folders WHERE id=?", (parent_id,))
                if cursor.fetchone()[0] == 0:
                    raise ValueError(f"父文件夹ID {parent_id} 不存在")
                    
                # 获取最大display_order
                cursor.execute("SELECT MAX(display_order) FROM folders WHERE parent_id=?", (parent_id,))
                max_order = cursor.fetchone()[0] or 0
                logging.info(f"获取到最大display_order: {max_order}")
                
                cursor.execute(
                    "INSERT INTO folders (name, user_id, parent_id, display_order, created_at) VALUES (?, ?, ?, ?, ?)",
                    (name.strip(), self.user_id, parent_id, max_order + 1, datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
                )
                conn.commit()
                logging.info(f"文件夹创建成功: {name}")
                self.load_folders()
                self.status_bar.showMessage(f"已创建文件夹: {name}")
            except Exception as e:
                logging.error(f"创建文件夹失败: {str(e)}")
                QMessageBox.critical(self, "错误", f"创建文件夹失败: {str(e)}")
            finally:
                conn.close()

    def move_folder(self, folder_id, target_folder_id):
        """移动文件夹到目标文件夹"""
        if folder_id == target_folder_id:
            QMessageBox.warning(self, "提示", "不能将文件夹移动到自身")
            return
        
        # 检查目标文件夹是否是当前文件夹的子文件夹
        def is_descendant(parent_id, child_id):
            conn = connect_db()
            cursor = conn.cursor()
            try:
                sql = '''WITH RECURSIVE subfolders AS (
                        SELECT id FROM folders WHERE parent_id = ?
                        UNION ALL
                        SELECT f.id FROM folders f
                        JOIN subfolders sf ON f.parent_id = sf.id
                        )
                        SELECT COUNT(*) FROM subfolders WHERE id = ?'''
                cursor.execute(sql, (parent_id, child_id))
                result = cursor.fetchone()
                return result[0] > 0
            except Exception as e:
                logging.error(f"检查子文件夹关系失败: {str(e)}")
                return False
            finally:
                conn.close()
        
        if is_descendant(folder_id, target_folder_id):
            QMessageBox.warning(self, "提示", "不能将文件夹移动到其子文件夹中")
            return
        
        conn = connect_db()
        cursor = conn.cursor()
        try:
            cursor.execute("UPDATE folders SET parent_id=?, updated_at=? WHERE id=?",
                          (target_folder_id, datetime.now().strftime('%Y-%m-%d %H:%M:%S'), folder_id))
            conn.commit()
            self.load_folders()
            self.status_bar.showMessage("文件夹已移动")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"移动文件夹失败: {str(e)}")
        finally:
            conn.close()
    
    def show_folder_context_menu(self, position):
        """显示文件夹右键菜单"""
        item = self.folder_tree.itemAt(position)
        if not item:
            return
        
        folder_id = item.data(0, Qt.ItemDataRole.UserRole)
        is_root = folder_id and is_root_folder(folder_id)
        
        menu = QMenu()
        
        # 新建子文件夹菜单项
        new_subfolder_action = menu.addAction("新建子文件夹")
        new_subfolder_action.triggered.connect(lambda: self.add_folder(folder_id))
        
        menu.addSeparator()
        
        # 重命名菜单项
        rename_action = menu.addAction("重命名")
        rename_action.triggered.connect(self.rename_folder)
        rename_action.setEnabled(not is_root)
        
        # 移动菜单项
        move_action = menu.addAction("移动")
        move_action.triggered.connect(lambda: self.show_move_dialog(folder_id))
        move_action.setEnabled(not is_root)
        
        # 删除菜单项
        delete_action = menu.addAction("删除")
        delete_action.triggered.connect(self.delete_folder)
        delete_action.setEnabled(not is_root)
        
        # 显示菜单
        menu.exec(self.folder_tree.mapToGlobal(position))
    
    def show_move_dialog(self, folder_id):
        """显示移动文件夹对话框"""
        # 创建对话框
        dialog = QDialog(self)
        dialog.setWindowTitle("移动文件夹")
        dialog.setMinimumWidth(400)
        
        layout = QVBoxLayout(dialog)
        
        # 选择目标文件夹的树
        layout.addWidget(QLabel("选择目标文件夹:"))
        target_tree = QTreeWidget()
        target_tree.setHeaderLabel("文件夹")
        target_tree.setMinimumHeight(300)
        
        # 加载文件夹树（排除当前文件夹及其子文件夹）
        def load_target_folders(exclude_id):
            conn = connect_db()
            cursor = conn.cursor()
            try:
                # 获取根文件夹
                cursor.execute("SELECT id, name FROM folders WHERE parent_id IS NULL")
                root_data = cursor.fetchone()
                if root_data:
                    root_id, root_name = root_data
                    root_item = QTreeWidgetItem(target_tree, [root_name])
                    root_item.setData(0, Qt.ItemDataRole.UserRole, root_id)
                    
                    # 递归加载子文件夹，排除指定文件夹
                    load_target_subfolders(root_item, root_id, exclude_id)
                    target_tree.expandItem(root_item)
            except Exception as e:
                logging.error(f"加载目标文件夹失败: {str(e)}")
            finally:
                conn.close()
        
        def load_target_subfolders(parent_item, parent_id, exclude_id):
            conn = connect_db()
            cursor = conn.cursor()
            try:
                cursor.execute("SELECT id, name FROM folders WHERE parent_id = ?", (parent_id,))
                subfolders = cursor.fetchall()
                for folder_id, folder_name in subfolders:
                    if folder_id == exclude_id:
                        continue
                    item = QTreeWidgetItem(parent_item, [folder_name])
                    item.setData(0, Qt.ItemDataRole.UserRole, folder_id)
                    load_target_subfolders(item, folder_id, exclude_id)
            except Exception as e:
                logging.error(f"加载子文件夹失败: {str(e)}")
            finally:
                conn.close()
        
        load_target_folders(folder_id)
        layout.addWidget(target_tree)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        button_layout.addStretch(1)
        
        cancel_btn = QPushButton("取消")
        cancel_btn.clicked.connect(dialog.reject)
        button_layout.addWidget(cancel_btn)
        
        move_btn = QPushButton("移动")
        move_btn.clicked.connect(lambda: self.on_move_confirmed(folder_id, target_tree, dialog))
        button_layout.addWidget(move_btn)
        
        layout.addLayout(button_layout)
        
        dialog.exec()
    
    def on_move_confirmed(self, folder_id, target_tree, dialog):
        """确认移动文件夹"""
        selected_item = target_tree.currentItem()
        if not selected_item:
            QMessageBox.warning(self, "提示", "请选择目标文件夹")
            return
        
        target_folder_id = selected_item.data(0, Qt.ItemDataRole.UserRole)
        self.move_folder(folder_id, target_folder_id)
        dialog.accept()
    
    def delete_folder(self):
        """删除文件夹"""
        current_item = self.folder_tree.currentItem()
        if not current_item:
            QMessageBox.warning(self, "提示", "请先选择文件夹")
            return

        folder_id = current_item.data(0, Qt.ItemDataRole.UserRole)
        # 检查是否为根文件夹
        if folder_id and is_root_folder(folder_id):
            QMessageBox.warning(self, "提示", "根文件夹'我的文档'不能删除")
            return

        if folder_id:
            reply = QMessageBox.question(
                self, "确认删除", "确定要删除此文件夹及所有文件吗?",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
            )
            if reply == QMessageBox.StandardButton.Yes:
                conn = connect_db()
                cursor = conn.cursor()
                try:
                    # 删除文件夹下的所有文件
                    cursor.execute("DELETE FROM files WHERE folder_id=?", (folder_id,))
                    # 删除文件夹
                    cursor.execute("DELETE FROM folders WHERE id=?", (folder_id,))
                    conn.commit()
                    self.load_folders()
                    self.file_list.clear()
                    self.status_bar.showMessage("文件夹已删除")
                except Exception as e:
                    QMessageBox.critical(self, "错误", f"删除文件夹失败: {str(e)}")
                finally:
                    conn.close()

    def rename_folder(self):
        """重命名文件夹"""
        current_item = self.folder_tree.currentItem()
        if not current_item:
            QMessageBox.warning(self, "提示", "请先选择文件夹")
            return

        folder_id = current_item.data(0, Qt.ItemDataRole.UserRole)
        # 检查是否为根文件夹
        if folder_id and is_root_folder(folder_id):
            QMessageBox.warning(self, "提示", "根文件夹'我的文档'不能重命名")
            return
        old_name = current_item.text(0)
        name, ok = QInputDialog.getText(self, "重命名文件夹", "请输入新名称:", text=old_name)


        if ok and name.strip() and name != old_name:
            conn = connect_db()
            cursor = conn.cursor()
            try:
                cursor.execute(
                    "UPDATE folders SET name=?, updated_at=? WHERE id=?",
                    (name.strip(), datetime.now().strftime('%Y-%m-%d %H:%M:%S'), folder_id)
                )
                conn.commit()
                current_item.setText(0, name.strip())
                self.status_bar.showMessage(f"文件夹已重命名为: {name}")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"重命名文件夹失败: {str(e)}")
            finally:
                conn.close() 

    def add_file(self):
        """新建文件 - 直接清空编辑区域，让用户开始输入"""
        if not self.current_folder_id:
            QMessageBox.warning(self, "提示", "请先选择一个文件夹")
            return

        # 清空当前编辑区域，准备新建文件
        self.current_file_id = None
        self.filename_edit.clear()
        self.editor.clear()
        self.need_save = False
        
        # 提示用户直接输入标题和内容
        self.status_bar.showMessage("请在上方输入文件名，下方输入内容，系统会自动保存")
        
        # 聚焦到文件名输入框
        self.filename_edit.setFocus()

    def delete_file(self):
        """删除文件"""
        current_item = self.file_list.currentItem()
        if not current_item:
            QMessageBox.warning(self, "提示", "请先选择文件")
            return

        file_id = current_item.data(0, Qt.ItemDataRole.UserRole)
        if file_id:
            reply = QMessageBox.question(
                self, "确认删除", "确定要删除此文件吗?",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
            )
            if reply == QMessageBox.StandardButton.Yes:
                conn = connect_db()
                cursor = conn.cursor()
                try:
                    cursor.execute("DELETE FROM files WHERE id=?", (file_id,))
                    conn.commit()
                    self.load_files(self.current_folder_id)
                    self.current_file_id = None
                    self.filename_edit.clear()
                    self.editor.clear()
                    self.need_save = False  # 添加这一行，防止自动保存触发
                    self.status_bar.showMessage("文件已删除")
                except Exception as e:
                    QMessageBox.critical(self, "错误", f"删除文件失败: {str(e)}")
                finally:
                    conn.close()

    def backup_database(self):
        """备份数据库到SQL文件"""
        file_path, _ = QFileDialog.getSaveFileName(
            self, "保存备份文件", "", "SQL Files (*.sql)"
        )
        if not file_path:
            return

        try:
            conn = connect_db()
            # 获取数据库名称
            db_name = DB_NAME
            
            # 执行备份
            with open(file_path, 'w', encoding='utf-8') as f:
                # 备份用户表
                for line in conn.iterdump():
                    f.write('%s\n' % line)

            conn.close()
            QMessageBox.information(
                self, "备份成功", f"数据库已成功备份到: {file_path}"
            )
        except Exception as e:
            QMessageBox.critical(self, "备份失败", f"备份数据库时出错: {str(e)}")

    def restore_database(self):
        """从SQL文件恢复数据库"""
        # 确保DB_NAME已导入
        from database import DB_NAME, connect_db, update_database_schema
        
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择备份文件", "", "SQL Files (*.sql)"
        )
        if not file_path:
            return

        reply = QMessageBox.question(
            self, "确认恢复", "恢复数据库将覆盖现有数据，确定要继续吗?",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
        )
        if reply != QMessageBox.StandardButton.Yes:
            return

        try:
            # 关闭当前连接
            conn = connect_db()
            conn.close()

            # 删除现有数据库文件
            if os.path.exists(DB_NAME):
                os.remove(DB_NAME)
                print(f"已删除现有数据库文件: {DB_NAME}")

            # 直接恢复数据
            new_conn = connect_db()
            with open(file_path, 'r', encoding='utf-8') as f:
                sql_script = f.read()

            new_conn.executescript(sql_script)
            new_conn.close()

            # 更新数据库模式以确保兼容性
            update_database_schema()

            # 重新加载数据
            self.load_folders()
            if self.current_folder_id:
                self.load_files(self.current_folder_id)

            QMessageBox.information(
                self, "恢复成功", f"数据库已从: {file_path} 恢复成功"
            )
        except Exception as e:
            QMessageBox.critical(self, "恢复失败", f"恢复数据库时出错: {str(e)}")

    def show_file_context_menu(self, position):
        """显示文件右键菜单"""
        item = self.file_list.itemAt(position)
        if not item:
            return
        
        menu = QMenu()
        
        # 移动文件菜单项
        move_action = menu.addAction("移动文件")
        move_action.triggered.connect(self.show_move_file_dialog)
        
        # 重命名菜单项
        rename_action = menu.addAction("重命名")
        rename_action.triggered.connect(self.rename_file)
        
        # 删除菜单项
        delete_action = menu.addAction("删除")
        delete_action.triggered.connect(self.delete_file)
        
        # 在光标位置显示菜单
        menu.exec(self.file_list.mapToGlobal(position))
        
    def show_move_file_dialog(self):
        """显示移动文件对话框"""
        current_item = self.file_list.currentItem()
        if not current_item:
            QMessageBox.warning(self, "提示", "请先选择文件")
            return
        
        file_id = current_item.data(0, Qt.ItemDataRole.UserRole)
        if not file_id:
            QMessageBox.warning(self, "提示", "无法获取文件ID")
            return
        
        # 创建对话框
        dialog = QDialog(self)
        dialog.setWindowTitle("移动文件")
        dialog.resize(400, 300)
        
        # 布局
        layout = QVBoxLayout(dialog)
        
        # 文件夹树
        layout.addWidget(QLabel("选择目标文件夹:"))
        folder_tree = QTreeWidget()
        folder_tree.setHeaderLabel("文件夹")
        layout.addWidget(folder_tree)
        
        # 加载文件夹树
        conn = connect_db()
        cursor = conn.cursor()
        try:
            # 获取根文件夹
            root_folder_id = ensure_user_root_folder(self.user_id)
            if root_folder_id:
                cursor.execute("SELECT name FROM folders WHERE id=?", (root_folder_id,))
                root_name = cursor.fetchone()[0]
                
                # 创建根节点
                root_item = QTreeWidgetItem(folder_tree, [root_name])
                root_item.setData(0, Qt.ItemDataRole.UserRole, root_folder_id)
                
                # 递归加载子文件夹
                self._load_folders_for_move_dialog(cursor, root_item, root_folder_id)
                
                # 展开根节点
                folder_tree.expandItem(root_item)
        except Exception as e:
            logging.error(f"加载文件夹树失败: {str(e)}")
        finally:
            conn.close()
        
        # 按钮
        btn_layout = QHBoxLayout()
        ok_btn = QPushButton("确定")
        cancel_btn = QPushButton("取消")
        btn_layout.addWidget(ok_btn)
        btn_layout.addWidget(cancel_btn)
        layout.addLayout(btn_layout)
        
        # 连接信号
        def on_ok():
            target_item = folder_tree.currentItem()
            if target_item:
                target_folder_id = target_item.data(0, Qt.ItemDataRole.UserRole)
                if target_folder_id:
                    self.move_file(file_id, target_folder_id)
                    dialog.accept()
            else:
                QMessageBox.warning(self, "提示", "请选择目标文件夹")
        
        ok_btn.clicked.connect(on_ok)
        cancel_btn.clicked.connect(dialog.reject)
        
        # 显示对话框
        dialog.exec()
        
    def _load_folders_for_move_dialog(self, cursor, parent_item, parent_id):
        """为移动文件对话框递归加载子文件夹"""
        cursor.execute(
            "SELECT id, name FROM folders WHERE user_id=? AND parent_id=? ORDER BY display_order",
            (self.user_id, parent_id)
        )
        subfolders = cursor.fetchall()
        
        for folder_id, name in subfolders:
            item = QTreeWidgetItem(parent_item, [name])
            item.setData(0, Qt.ItemDataRole.UserRole, folder_id)
            
            # 递归加载孙子文件夹
            self._load_folders_for_move_dialog(cursor, item, folder_id)
    
    def move_file(self, file_id, target_folder_id):
        """移动文件到指定文件夹"""
        if not file_id or not target_folder_id:
            QMessageBox.warning(self, "提示", "文件ID或目标文件夹ID无效")
            return
        
        conn = connect_db()
        cursor = conn.cursor()
        try:
            # 检查文件是否存在
            cursor.execute("SELECT COUNT(*) FROM files WHERE id=?", (file_id,))
            if cursor.fetchone()[0] == 0:
                QMessageBox.warning(self, "提示", "文件不存在")
                return
            
            # 检查目标文件夹是否存在
            cursor.execute("SELECT COUNT(*) FROM folders WHERE id=? AND user_id=?", 
                          (target_folder_id, self.user_id))
            if cursor.fetchone()[0] == 0:
                QMessageBox.warning(self, "提示", "目标文件夹不存在或无权限访问")
                return
            
            # 更新文件的folder_id
            cursor.execute(
                "UPDATE files SET folder_id=?, updated_at=? WHERE id=?",
                (target_folder_id, datetime.now(), file_id)
            )
            conn.commit()
            
            # 重新加载文件列表
            self.load_files(self.current_folder_id)
            
            # 如果正在编辑的是被移动的文件，清除编辑区域
            if self.current_file_id == file_id:
                self.current_file_id = None
                self.filename_edit.clear()
                self.editor.clear()
                self.need_save = False
            
            self.status_bar.showMessage("文件已移动")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"移动文件失败: {str(e)}")
            logging.error(f"移动文件失败: {str(e)}")
        finally:
            conn.close()
    
    def rename_file(self):
        """重命名文件"""
        current_item = self.file_list.currentItem()
        if not current_item:
            QMessageBox.warning(self, "提示", "请先选择文件")
            return

        file_id = current_item.data(0, Qt.ItemDataRole.UserRole)
        old_name = current_item.text(0)
        name, ok = QInputDialog.getText(self, "重命名文件", "请输入新名称:", text=old_name)


        if ok and name.strip() and name != old_name:
            conn = connect_db()
            cursor = conn.cursor()
            try:
                cursor.execute(
                    "UPDATE files SET name=?, updated_at=? WHERE id=?",
                    (name.strip(), datetime.now(), file_id)
                )
                conn.commit()
                current_item.setText(0, name.strip())
                if self.current_file_id == file_id:
                    self.filename_edit.setText(name.strip())
                self.status_bar.showMessage(f"文件已重命名为: {name}")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"重命名文件失败: {str(e)}")
            finally:
                conn.close()


    def save_file(self, show_message=True):
        """保存文件内容"""
        filename = self.filename_edit.text().strip()
        if not filename:
            if show_message:
                QMessageBox.warning(self, "提示", "请输入文件名")
            return

        if not self.current_folder_id:
            if show_message:
                QMessageBox.warning(self, "提示", "请先选择一个文件夹")
            return

        content = self.editor.toHtml()
        conn = connect_db()
        cursor = conn.cursor()

        try:
            is_new_file = self.current_file_id is None
            
            if self.current_file_id:
                # 更新现有文件
                cursor.execute(
                        "UPDATE files SET name=?, content=?, updated_at=? WHERE id=?",
                        (filename, content, datetime.now(), self.current_file_id)
                    )
                if show_message:
                    self.status_bar.showMessage(f"文件已保存: {filename}")
            else:
                # 创建新文件
                cursor.execute(
                        "INSERT INTO files (name, folder_id, content, created_at, updated_at) VALUES (?, ?, ?, ?, ?)",
                        (filename, self.current_folder_id, content, datetime.now(), datetime.now())
                    )
                self.current_file_id = cursor.lastrowid
                # 总是刷新文件列表，不管show_message是什么
                self.load_files(self.current_folder_id)
                if show_message:
                    self.status_bar.showMessage(f"已创建并保存文件: {filename}")

            conn.commit()
            self.need_save = False
            if show_message:
                # 修正datetime的使用
                current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                self.statusBar().showMessage(f"文件保存成功 [{current_time}]")
            
            # 当首次自动保存新文件时，自动点击当前文件夹
            # 不依赖于show_message参数，确保自动保存时也能执行
            if is_new_file:
                # 查找当前文件夹对应的树节点
                def find_folder_item(tree_widget, folder_id):
                    for i in range(tree_widget.topLevelItemCount()):
                        item = tree_widget.topLevelItem(i)
                        if item and item.data(0, Qt.ItemDataRole.UserRole) == folder_id:
                            return item
                        # 递归查找子节点
                        found_item = find_child_folder_item(item, folder_id)
                        if found_item:
                            return found_item
                    return None
                
                def find_child_folder_item(parent_item, folder_id):
                    for i in range(parent_item.childCount()):
                        item = parent_item.child(i)
                        if item and item.data(0, Qt.ItemDataRole.UserRole) == folder_id:
                            return item
                        # 递归查找更深层级
                        found_item = find_child_folder_item(item, folder_id)
                        if found_item:
                            return found_item
                    return None
                
                # 查找并选中当前文件夹
                folder_item = find_folder_item(self.folder_tree, self.current_folder_id)
                if folder_item:
                    # 确保文件夹项可见
                    self.folder_tree.scrollToItem(folder_item)
                    # 设置为当前选中项
                    self.folder_tree.setCurrentItem(folder_item)
                    # 触发点击事件
                    self.on_folder_clicked(folder_item, 0)
        except Exception as e:
            if show_message:
                QMessageBox.critical(self, "错误", f"保存文件失败: {str(e)}")
        finally:
            conn.close()


    def auto_save(self):
        if self.need_save:
            try:
                self.save_file(show_message=False)
                # 修正datetime的使用
                current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                self.statusBar().showMessage(f"自动保存成功 [{current_time}]")
            except Exception as e:
                self.statusBar().showMessage(f"自动保存失败: {str(e)}")


    def apply_styles(self):
        """应用全局样式表"""
        style_sheet = f"""
        /* 全局样式 */
        QWidget {{
            background-color: {self.theme['background']};
            color: {self.theme['text']};
            font-family: 'Microsoft YaHei UI', 'SimSun';
            font-size: 12px;
        }}


        /* 标题标签 */
        QLabel[class='title'] {{
            font-size: 14px;
            font-weight: bold;
            color: {self.theme['primary']};
            padding: 5px 0;
        }}


        /* 按钮样式 */
        QPushButton {{
            background-color: {self.theme['secondary']};
            border: none;
            border-radius: 4px;
            padding: 6px 12px;
            font-size: 12px;
        }}
        QPushButton:hover {{
            background-color: {self.theme['primary_light']};
        }}
        QPushButton:pressed {{
            background-color: {self.theme['primary']};
            color: white;
        }}
        QPushButton:disabled {{
            background-color: #e0e0e0;
            color: #a0a0a0;
        }}


        /* 输入框样式 */
        QLineEdit, QTextEdit {{
            border: 1px solid {self.theme['border']};
            border-radius: 4px;
            padding: 8px;
            background-color: white;
        }}
        QLineEdit:focus, QTextEdit:focus {{
            border-color: {self.theme['primary']};
            outline: none;
        }}


        /* 树形视图样式 */
        QTreeWidget {{
            border: 1px solid {self.theme['border']};
            border-radius: 4px;
            background-color: white;
            alternate-background-color: {self.theme['panel_bg']};
        }}
        QTreeWidget::item:hover {{
            background-color: {self.theme['primary_light']};
        }}
        QTreeWidget::item:selected {{
            background-color: {self.theme['primary']};
            color: white;
        }}
        QTreeWidget::header {{
            background-color: {self.theme['secondary']};
            padding: 6px;
            border: none;
        }}


        /* 分割器样式 */
        QSplitter::handle {{ 
            background-color: {self.theme['border']};
            width: 4px;
            height: 4px;
        }}
        QSplitter::handle:hover {{ 
            background-color: {self.theme['primary_light']};
        }}


        /* 工具栏样式 */
        QToolBar {{
            background-color: {self.theme['panel_bg']};
            border: none;
            spacing: 10px;
            padding: 5px;
        }}
        """
        self.setStyleSheet(style_sheet)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    # 这里需要替换为实际的用户ID验证逻辑
    window = PyQtMainWindow(user_id=1)
    window.show()
    sys.exit(app.exec())